package cn.com.chengmandian.core.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONObject;

import java.io.File;
import java.io.InputStream;
import java.util.*;

public class ExcelDataUtil {

    /**
     * 数据列表转换为文件
     * @param header
     * @param rows
     * @return
     */
    public static File dataListToFile(List<String> header, List<List<String>> rows, String filePath) {
        File file = new File(System.getProperty("user.dir") + File.separator + filePath);
        ExcelWriter excelWriter = ExcelUtil.getWriter(file);
        excelWriter.writeRow(header, true);
        excelWriter.write(rows);
        excelWriter.close();
        return file;
    }

    /**
     * 获取默认excel文件路径
     * @return
     */
    public static String getRandomExcelFilePath() {
        return "excel" + File.separator
                + DateUtil.format(new Date(), "yyyy") + File.separator
                + DateUtil.format(new Date(), "MMdd") + File.separator
                + RandomUtil.randomString(30) +".xls";
    }

    /**
     * 表格转换城数据列表
     * 默认第一行是标题行
     * @param inputStream
     * @return
     */
    public static List<JSONObject> fileToDataList(InputStream inputStream) {
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        List<List<Object>> dataList = reader.read();
        Map<String, Integer> header = new HashMap<>();
        int rowNumber = 0;
        List<JSONObject> list = new ArrayList<>();
        for(List<Object> row : dataList) {
            if (rowNumber == 0) {
                int cellNumber = 0;
                for (Object cell : row) {
                    if (cell != null && !cell.toString().equals("")) {
                        header.put(cell.toString(), cellNumber);
                    }
                    cellNumber = cellNumber + 1;
                }
            } else {
                JSONObject item = new JSONObject();
                for (String key : header.keySet()) {
                    Integer headerIndex = header.get(key);
                    if(headerIndex < row.size()) {
                        item.put(key, objectToStr(row.get(headerIndex)));
                    }else{
                        item.put(key, objectToStr(""));
                    }
                }
                list.add(item);
            }
            rowNumber = rowNumber + 1;
        }
        return list;
    }

    private static String objectToStr(Object data) {
        return data == null ? "" : data.toString();
    }
}
